﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using Newtonsoft.Json.Linq;
using System.Text;
using System.Windows.Forms;

using System.Net;
using System.IO;
using System.Threading;
using System.Collections;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.DirectX.AudioVideoPlayback;
using System.Management;

namespace WindowsFormsApplication2
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			if (AppAlreadyRunning())
				Environment.Exit(0);
			InitializeComponent();
			this.FormBorderStyle = FormBorderStyle.None;//不显示标题栏
			music_Select("open");//显示频道选择
			this.Show();
			this.TopMost = true;
			//开启音乐
			//webBrowser3.Url = new Uri("http://douban.fm/");
			label1.Text = "当前版本:" + Application.ProductVersion;
		}
		private bool AppAlreadyRunning()//返回当前程序是否已运行实例
		{
			System.Diagnostics.Process curProcess = System.Diagnostics.Process.GetCurrentProcess();
			System.Diagnostics.Process[] allProcess = System.Diagnostics.Process.GetProcesses();
			foreach (System.Diagnostics.Process process in allProcess)
			{
				if (process.Id != curProcess.Id)
				{
					if (process.ProcessName == curProcess.ProcessName)
						return true;
				}
			}
			return false;
		}
		private WebClient client = new WebClient();//抓取对象实例化
		private void music_Select(string action)//显示电台选项
		{
			if (action == "off")
			{
				radioButton1.Visible = false;
				radioButton2.Visible = false;
				radioButton3.Visible = false;
				radioButton4.Visible = false;
				radioButton5.Visible = false;
				radioButton6.Visible = false;
				radioButton7.Visible = false;
				radioButton8.Visible = false;
			}
			if (action == "open")
			{
				radioButton1.Visible = true;
				radioButton2.Visible = true;
				radioButton3.Visible = true;
				radioButton4.Visible = true;
				radioButton5.Visible = true;
				radioButton6.Visible = true;
				radioButton7.Visible = true;
				radioButton8.Visible = true;
			}
		}
		int last_Station = 0;//上一个电台
		private delegate void worker_channel_Selection(int station);
		private delegate int worker_download_mp3(string[] url, string[] name);//后台下载mp3
		public bool downloading_flag = false;//标记是否正在下载
		public int download_mp3(string[] url, string[] name)//下载mp3
		{
			if (!downloading_flag)
			{
				downloading_flag = true;
				string file_long = System.Environment.CurrentDirectory + @"\Resources\mp3";
				if (!Directory.Exists(@file_long))//若文件夹不存在则新建文件夹
				{
					Directory.CreateDirectory(@file_long); //新建文件夹
				}
				else if (System.IO.File.Exists(@"Resources\mp3\tmpmp3"))//如果存在文件夹，则检查是否有临时下载，有则删除。
				{
					File.Delete(@"Resources\mp3\tmpmp3");//删除下载中断的文件
				}
				for (int i = 0; i < 4; i++)
				{
					client.DownloadFile(url[i], @"Resources\mp3\tmpmp3");//下载mp3到临时文件
					File.Move(@"Resources\mp3\tmpmp3", name[i]);//修改临时文件名到正常文件名，以预防下载中断
				}
				downloading_flag = false;
			}
			return 1;
		}
		string[] mp3_url_list = new string[4]{"","","",""};
		string[] mp3_name_list = new string[4];
		private void channel_Selection_(int station)//选择电台  后台
		{
			if (last_Station != station)//如果改变电台，则切换
			{
				last_Station = station;//保存正在播放的电台
				string url = "http://douban.fm/?cid=" + station;
				webBrowser3.Url = new Uri(url);
				Thread.Sleep(10000);//换台时，暂停10s以缓冲正在播放的。
			}
			string playlist;
			if (!downloading_flag)
			{
				downloading_flag = true;
				string station_url = "http://douban.fm/j/mine/playlist?type=n&sid=181855&pt=4.5&channel=" + station + "&r=f28dc2ca86";
				downloading_flag = false;
				playlist = GetWebContent(station_url);
				if (playlist.Length >= 1500)
				{
					JObject jo = JObject.Parse(playlist);
					for (int i = 0; i < 4; i++)
					{
						mp3_url_list[i] = jo["song"][i]["url"].ToString();
						mp3_name_list[i] = "Resources/mp3/p" + jo["song"][i]["sid"].ToString() + ".mp3";
					}
					worker_download_mp3 afd = download_mp3;//后台调用下载，这样会是前台卡死。
					afd.BeginInvoke(mp3_url_list, mp3_name_list, null, null);//下载mp3
					//Audio audio = new Audio(jo["song"][0]["url"].ToString());//缓冲播放
					//audio.Play();//播放
				}
			} 		
		}
		private void channel_Selection(int station)//选择电台
		{
			worker_channel_Selection afd = channel_Selection_;
			afd.BeginInvoke(station,null, null);//调用后台
		}
		// 切换频道 开始
		private void radioButton12_CheckedChanged(object sender, EventArgs e)//空白模式
		{
			webBrowser3.Url = new Uri("http://www.baidu.com/");
		}

		private void radioButton11_CheckedChanged(object sender, EventArgs e)//随机模式
		{
			string url = "http://douban.fm/";
			webBrowser3.Url = new Uri(url);
		}

		private void radioButton1_CheckedChanged(object sender, EventArgs e)
		{
			webBrowser3.Url = new Uri("http://douban.fm/?context=channel:0|musician_id:103939");
		}

		private void radioButton2_CheckedChanged(object sender, EventArgs e)
		{
			channel_Selection(32);
		}

		private void radioButton3_CheckedChanged(object sender, EventArgs e)
		{
			channel_Selection(2);
		}

		private void radioButton4_CheckedChanged(object sender, EventArgs e)
		{
			channel_Selection(1);
		}

		private void radioButton5_CheckedChanged(object sender, EventArgs e)
		{
			channel_Selection(6);
		}

		private void radioButton6_CheckedChanged(object sender, EventArgs e)
		{
			channel_Selection(9);
		}

		private void radioButton7_CheckedChanged(object sender, EventArgs e)
		{
			channel_Selection(5);
		}

		private void radioButton8_CheckedChanged(object sender, EventArgs e)
		{
			channel_Selection(8);
		}

		private void radioButton9_CheckedChanged(object sender, EventArgs e)
		{
			channel_Selection(76);
		}

		private void radioButton10_CheckedChanged(object sender, EventArgs e)
		{
			channel_Selection(1000606);
		}
		// 切换频道 结束

		private string GetWebContent(string sUrl)//抓取网页
		{
			string strResult = "";
			try
			{
				HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sUrl);
				//声明一个HttpWebRequest请求
				request.Timeout = 3000;
				//设置连接超时时间
				request.Headers.Set("Pragma", "no-cache");
				HttpWebResponse response = (HttpWebResponse)request.GetResponse();
				if (response.ToString() != "")
				{
					Stream streamReceive = response.GetResponseStream();
					Encoding encoding = Encoding.GetEncoding("UTF-8");
					StreamReader streamReader = new StreamReader(streamReceive, encoding);
					strResult = streamReader.ReadToEnd();
				}
			}
			catch (WebException e)
			{
				strResult = "";
			}
			return strResult;
		}

		//C#窗体隐藏标题栏后,鼠标可拖动窗口的代码
		private bool m_isMouseDown = false;
		private Point m_mousePos = new Point();
		protected override void OnMouseDown(MouseEventArgs e)
		{
			base.OnMouseDown(e);
			m_mousePos = Cursor.Position;
			m_isMouseDown = true;
		}

		protected override void OnMouseUp(MouseEventArgs e)
		{
			base.OnMouseUp(e);
			m_isMouseDown = false;
		}

		protected override void OnMouseMove(MouseEventArgs e)
		{
			base.OnMouseMove(e);
			if (m_isMouseDown)
			{
				Point tempPos = Cursor.Position;
				this.Location = new Point(Location.X + (tempPos.X - m_mousePos.X), Location.Y + (tempPos.Y - m_mousePos.Y));
				m_mousePos = Cursor.Position;
			}
		}
		//C#窗体隐藏标题栏后,鼠标可拖动窗口的代码

		private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)//关于信息
		{
			MessageBox.Show("我们还将推出音乐搜索功能，歌手点播、专辑点播、流派点播，以及小说、视频、电影观看功能。\n\n                        1117班合力开发");
		}

	

		bool top_most = false;//是否最前端
		private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)//系统推盘处，点击显示出主程序
		{
			if (top_most)
			{
				this.Hide();
				top_most = false;
			}
			else
			{
				this.Show();
				this.TopMost = true;
				top_most = true;
			}
		}

		private void pictureBox1_Click(object sender, EventArgs e)//最小化按钮
		{
			top_most = false;
			this.Hide();
		}

		private void pictureBox2_Click(object sender, EventArgs e)//退出按钮
		{
			Application.Exit();
		}

		private void timer1_Tick(object sender, EventArgs e)//启动后延迟更新Update.exe
		{
			internet_connet internet_connet =new internet_connet();
			if (internet_connet.IsConnected()&!downloading_flag)
			{
				downloading_flag = true;//下载占用
				String strFileVersion = "0";//版本号
				string server_Status = GetWebContent("http://soft.weibodangan.com/server_Status.php" + "?version=" + Application.ProductVersion) + "&disk=" + GetDiskVolumeSerialNumber() + "&mac=" + GetMoAddress();
				if (System.IO.File.Exists(@"Update.exe"))//检测Update.exe是否存在
				{
					FileVersionInfo myFileVersion = FileVersionInfo.GetVersionInfo("Update.exe");
					strFileVersion = string.Format("{0}.{1}.{2}.{3}", myFileVersion.FileMajorPart, myFileVersion.FileMinorPart, myFileVersion.FileBuildPart, myFileVersion.FilePrivatePart);//
				}
				else
				{
					strFileVersion = "0";
				}

				if (server_Status == "server_Status_is_ok" && strFileVersion != GetWebContent("http://soft.weibodangan.com/Version_Update.php"))//检测网络状态和检查版本号
				{
					client.DownloadFile("http://soft.weibodangan.com/Update.exe", "Update.exe");//更新update.exe
					label2.Text = "最新版本:" + GetWebContent("http://soft.weibodangan.com/Version.php");
					timer1.Enabled = false;
				}
				else if (server_Status == "server_Status_is_ok")
				{
					label2.Text = "最新版本:" + GetWebContent("http://soft.weibodangan.com/Version.php");
					timer1.Enabled = false;
				}
				downloading_flag = false;//下载释放
			}
			timer1.Interval = timer1.Interval * 2;//每次重试时间*2 
		}
		//取得硬盘序列号
		private ManagementClass mc;
		private ManagementObjectCollection moc;
		private ManagementObject disk;
		public string GetDiskVolumeSerialNumber()
		{
			mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
			disk = new ManagementObject("win32_logicaldisk.deviceid=\"c:\"");
			disk.Get();
			return disk.GetPropertyValue("VolumeSerialNumber").ToString();
		}
		public string GetMoAddress()//取得网卡硬件地址
		{
			string MoAddress = "";
			ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
			ManagementObjectCollection moc2 = mc.GetInstances();
			foreach (ManagementObject mo in moc2)
			{
				if ((bool)mo["IPEnabled"] == true)
					MoAddress = mo["MacAddress"].ToString();
				mo.Dispose();
			}
			return MoAddress.ToString();
		}

		public static bool IsFileInUse(string fileName)//判断文件是否正在被使用
		{
			bool inUse = true;

			FileStream fs = null;
			try
			{

				fs = new FileStream(fileName, FileMode.Open, FileAccess.Read,

				FileShare.None);

				inUse = false;
			}
			catch
			{

			}
			finally
			{
				if (fs != null)

					fs.Close();
			}
			return inUse;//true表示正在使用,false没有使用
		}


		bool detail = false;//标记详细模式是否开启
		private void button1_Click(object sender, EventArgs e)//详细模式
		{
			if (detail)
			{
				detail = false;
				button1.Text = "详细模式";
				this.pictureBox1.Location = new System.Drawing.Point(126, 8);
				this.pictureBox2.Location = new System.Drawing.Point(169, 8);
				this.ClientSize = new System.Drawing.Size(206, 606);
				axShockwaveFlash1.Visible = false;
				axShockwaveFlash1.Movie = Directory.GetCurrentDirectory() + "/Resources/flash/null.swf"; ;//注意路径要使用完整路径

			}
			else
			{
				detail = true;
				button1.Text = "简单模式";
				this.pictureBox1.Location = new System.Drawing.Point(126 + 214, 8);
				this.pictureBox2.Location = new System.Drawing.Point(169 + 214, 8);
				this.ClientSize = new System.Drawing.Size(206 + 214, 606 - 320);
				this.axShockwaveFlash1.Location = new System.Drawing.Point(0, 78);
				axShockwaveFlash1.Visible = true;
				axShockwaveFlash1.Movie = Directory.GetCurrentDirectory() + "/Resources/flash/radioplayer.swf";//注意路径要使用完整路径
			}
		}

		private void paly_work_Tick(object sender, EventArgs e)//后台下载
		{
			if (!downloading_flag)//如果没有在下载
			{
				channel_Selection(last_Station);
			}
		}
	}
	public class internet_connet//检测是否有网络连接
	{
		[DllImport("wininet.dll ")]
		private extern static bool InternetGetConnectedState(out   int connectionDescription, int reservedValue);
		public internet_connet()
		{ }
		public bool IsConnected()
		{
			int I = 0;
			bool state = InternetGetConnectedState(out   I, 0);
			return state;
		}
	}
}
